package com.yc.fav.servelet;

import com.google.gson.Gson;
import com.yc.fav.entity.User;
import com.yc.fav.service.BizException;
import com.yc.fav.service.IUserService;
import com.yc.fav.service.impl.UserServiceImpl;
import com.yc.fav.vo.Result;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginSevelet extends HttpServlet {
    IUserService userService=new UserServiceImpl();
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        Result ret;
        try {
            User user = userService.login(username, password);
            ret=new Result(1,"登录成功",user);
            request.getSession().setAttribute("myinfo",user);
        } catch (BizException e) {
            ret=new Result(e.getCode(),e.getMessage(),null);
        }
        String json=new Gson().toJson(ret);
        response.getWriter().append(json);
    }
}
